﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace foriisexpress
{
    public partial class upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Request.HttpMethod == "GET")
            {
                Response.Write("{\"code\":-1,\"error\":\"this is a post method,so post a file to here.\"}");
                return;
            }
            HttpPostedFile file = this.Request.Files[0];
            if (file.ContentLength == 0)
            {
                Response.Write("{\"code\":-2,\"error\":\"file length to small.\"}");
                return;
            }
            if (file.ContentLength > 1024 * 1024 * 4)
            {
                Response.Write("{\"code\":-3,\"error\":\"file length to large.\"}");
                return;
            }

            string path = this.Request.Params["path"];

            byte[] fileinfo = new byte[file.ContentLength];
            int iread = file.InputStream.Read(fileinfo, 0, fileinfo.Length);

            string sPath = Page.Server.MapPath("/");
            var backone = System.IO.Path.GetDirectoryName(sPath);
            path = path.Replace('/', System.IO.Path.DirectorySeparatorChar);
            var filename = System.IO.Path.Combine(backone, path);
            var filepath = System.IO.Path.GetDirectoryName(filename);
            if (System.IO.Directory.Exists(filepath) == false)
                System.IO.Directory.CreateDirectory(filepath);
            System.IO.File.WriteAllBytes(filename, fileinfo);

            this.Response.Write("{\"code\":0,\"path\":\"" + Uri.EscapeDataString(backone) + "\"}");
        }
    }
}